package com.handu.luna.mall.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.search.Search4Portal;
import com.handu.luna.core.domain.search.Search4Portal.SearchOrCategory;
import com.handu.luna.core.domain.support.GoodsGroupInfo;

/**
 * @title:SearchController.java
 * @package com.handu.luna.mall.controller
 * @author 张恒强
 * @date 2014年9月16日 下午3:42:20
 * @version V1.0
 */
@Controller
@RequestMapping("/search/*")
public class SearchController extends BaseController{
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("index")
	public MallModelView index(Search4Portal sportal){
		if(sportal == null){
			sportal = new Search4Portal();
		}
		sportal.setSc(SearchOrCategory.SEARCH);
		Goods goods = new Goods();
		List finalData = goods.search4Portal(sportal);
		//搜索框 属性
		Map<GoodsGroupInfo, List<GoodsGroupInfo>> topSearchGroupByAttribute =
				goods.groupByAttribute(sportal, finalData);
		//搜索框 品牌
		Map<Long,GoodsGroupInfo> topSearchGroupByBrand = 
				goods.groupByBrand(sportal, finalData);
		//搜索框 分类
		
		//分页 排序  商品列表
		Page<Goods> currentPage;
		if(CollectionUtils.isNotEmpty(finalData) && CollectionUtils.isNotEmpty((Collection) finalData.get(0))){
			currentPage = new PageImpl<Goods>(
					 (List<Goods>) finalData.get(1), 
					 new PageRequest(sportal.getPage(), sportal.getPagesize()),
					 ((List<Long>)finalData.get(0)).size());
		}else{
			currentPage = new PageImpl<Goods>(
					 new ArrayList<Goods>(), 
					 new PageRequest(sportal.getPage(), sportal.getPagesize()),
					 0);
		}
		 DEBUG(currentPage);
		return buildModelView("/search/search").
				add("topSearchGroupByAttribute", topSearchGroupByAttribute).
				add("topSearchGroupByBrand", topSearchGroupByBrand).
				add("topSearchGroupByCategory", goods.groupByCategory(sportal, finalData)).
				add("currentPage", currentPage).
				add("sportal", sportal);
	}
	
	
}
